/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package post;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import post.dataaccess.ProductReader;
import post.dataaccess.TransactionReader;
import post.ui.Ui;

/**
 *
 * @author Harry
 */
public class Post {

    private static final String PRODUCT_FILE = "products.txt";
    private static final String TRANSACTION_FILE = "transaction.txt";    
    private Cashier cashier;
    private Store store;
    private ProductSpec[] products;

    public Post(Store store, Cashier cashier) {
        ProductReader productReader = null;    
        try {
            productReader = new ProductReader(PRODUCT_FILE);
        } catch (IOException ex) {
            Logger.getLogger(Post.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        this.store = new Store("Group 3","1234 Not a very creative name.CA 000000");
        this.cashier = cashier;
        products = productReader.loadAll();
         
    }

    public void Start() throws IOException, ParseException {
        String[] inputUpcArray = new String[100];
        String[] inputQtyArray = new String[100];
        String str;
        int n, i;
        boolean continueExec = true;
        String commandStr;
        ProductReader objProductReader = null;
        
        try {
            objProductReader = new ProductReader(PRODUCT_FILE);
        } catch (IOException ex) {
            Logger.getLogger(Post.class.getName()).log(Level.SEVERE, null, ex);
        }        
        TransactionReader objTransactionReader = null;
        try {
            objTransactionReader = new TransactionReader(store, TRANSACTION_FILE);
        } catch (Exception ex) {
            System.out.println("Here. "+ex.getMessage());
            Logger.getLogger(Post.class.getName()).log(Level.SEVERE, null, ex);
        }
        Payment payment = Payment.Cash;
        
        while (continueExec) {
            commandStr = Ui.showMenu();
            switch (Integer.parseInt(commandStr)) {
                case 1:
                    Customer objCustomer = new Customer(Ui.getCustomerName());
                    n = Ui.getTransactionItems(inputUpcArray, inputQtyArray);
                    TransactionItem[] transItems = new TransactionItem[n];                    
                    for (i = 0; i < n; i++) {                       
                        transItems[i] = new TransactionItem(inputUpcArray[i], Integer.parseInt(inputQtyArray[i]));                        
                    }
                    
                    str = Ui.getPaymentType();
                    
                    switch (Integer.parseInt(str)) {
                        case 1:
                            payment = Payment.Cash;
                            break;
                        case 2:
                            payment = Payment.Cheque;
                            break;
                        case 3:
                            payment = Payment.CreditCard;
                            break;
                    }
                    float paymentReceived=0;
                    int cardNum=0;
                    if (payment==Payment.Cash){
                         paymentReceived=Ui.getCashTendered();
                    }
                    else
                         paymentReceived=0;
                    if (payment==Payment.CreditCard){
                         cardNum=Ui.getCreditCardNum();
                    }
                   
                    Date date = new Date();
                    TransactionHeader objTransactionHeader = new TransactionHeader(store, cashier);
                    Transaction objTransaction = new Transaction(objCustomer.getName(), transItems, payment, date, n, objTransactionHeader,paymentReceived,cardNum);                     
                     
            try {
                objTransactionReader.addTransaction(objTransaction,objProductReader);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                Logger.getLogger(Post.class.getName()).log(Level.SEVERE, null, ex);
            }
            
                    //Printing Invoice
                    float total = 0;
                    SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
                    String invoice = store.getName() + "\r\n\r\n" + objCustomer.getName() + "   " + date_format.format(date) + "\r\n";
                    
                    for (i = 0; i < n; i++) {
                        invoice += "Item: ";

                        for (ProductSpec ps : products) {                            
                            if (transItems[i].getUpc().equals(ps.getUpc())) {
                                invoice += ps.getDescription() + "  " + transItems[i].getQuantity() + "  " + ps.getPrice() + "  " + String.valueOf(ps.getPrice() * transItems[i].getQuantity());
                                total += (ps.getPrice()) * (transItems[i].getQuantity());
                                
                                break;
                            }
                            
                        }                        
                        invoice += "\r\n";
                    }
                    
                    invoice += "------\r\n";
                    String payTypeInfo=new String();
                    if (payment==Payment.Cash){
                        payTypeInfo="\nAmount Tendered: $" + paymentReceived +"Balance : "+(paymentReceived-total);
                    }
                    if (payment==Payment.CreditCard){
                        payTypeInfo="\nCard Number : "+cardNum;
                    }
                    invoice += "Total: $" + total +" Paid by " + payment.name()+payTypeInfo ;                    
                    Ui.printInvoice(invoice);

                    break;
                case 2:
                    Ui.addProduct(inputUpcArray);
            try {
                objProductReader.addProduct(new ProductSpec(inputUpcArray[1], inputUpcArray[0], Float.parseFloat(inputUpcArray[2])),PRODUCT_FILE);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Post.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Post.class.getName()).log(Level.SEVERE, null, ex);
            }
                    break;
                case 3:
                    String myUpc;
                    myUpc = Ui.getUpc();
                    for (ProductSpec ps : products) {
                        if ((ps.getUpc()).compareTo(myUpc)==0) {
                            inputUpcArray[0] = String.valueOf(ps.getUpc());
                            inputUpcArray[1] = ps.getDescription();
                            inputUpcArray[2] = String.valueOf(ps.getPrice());
                            break;
                        }
                    }
                    Ui.printProductInfo(inputUpcArray);
                    break;
                case 4: objProductReader.printProductsSortedByName();
                    break;
                case 5:System.out.println("Enter Date in mm/dd/yyyy format :");
                      InputStreamReader isr = new InputStreamReader(System.in);
                      BufferedReader br = new BufferedReader(isr);
                      str = br.readLine();
                      Date date1=new SimpleDateFormat("MM/dd/yyyy").parse(str);                     
                      
                      String[] tempTrans1=objTransactionReader.getTransactionByDate(date1);
                        for ( i=0;i<tempTrans1.length&&tempTrans1[i]!=null;i++)
                        {
                            System.out.println(tempTrans1[i]);
                        }
                    break;
                case 6:System.out.println("Enter Customer Name :");
                        InputStreamReader isr1 = new InputStreamReader(System.in);
                        BufferedReader br1 = new BufferedReader(isr1);
                        str = br1.readLine();
                        String[] tempTrans=objTransactionReader.getTransactionByCustomerName(str);
                        for ( i=0;i<tempTrans.length&&tempTrans[i]!=null;i++)
                        {
                            System.out.println(tempTrans[i]);
                        }
                    break;
                case 7:
                    continueExec = false;
                    break;
                default:
                    Ui.invalidCommand();
                    break;
            }
        }
    }
    /**
     * @param args the command line arguments
     */
//    public static void main(String[] args) {
//        // TODO code application logic here
//    }
}
